//
//  WBTabBarViewController.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/5/9.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBTabBarViewController: UITabBarController {
    
    ///定时器
    var timer: Timer?
    
    //MARK: -私有属性
    ///撰写按钮
    lazy var composeButton : UIButton = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        
        setupComposeButton()
        
        setupNewFeature()
        
        setupTimer()
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
        delegate = self
    }
    
    deinit {
        
        //销毁定时器
        timer?.invalidate()
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    ///横竖屏处理
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    
    //MARK: - 监听事件
    ///撰写按钮的点击事件
    //FIXME:还没有写
    @objc fileprivate func composeButtonClick() {
        print("composeButtonClick")
        
        let vc = UIViewController()
        
        vc.view.backgroundColor = UIColor().randomColor
        
        let navi = UINavigationController(rootViewController: vc)
        
        present(navi, animated: true, completion: nil)
    }
    
    /// 监听用户登录通知事件
    ///
    /// - Parameter noti: 用户登录通知
    @objc private func userLogin(noti: Notification) {
        
        print("用户登录通知")
        
        if noti.object != nil {
            
            SVProgressHUD.setDefaultMaskType(.black)
            
            SVProgressHUD.showInfo(withStatus: WBLoginTimeout)
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            //展现webView
            let vc = WBOAuthViewController()
            
            let navi = UINavigationController(rootViewController: vc)
            
            self.present(navi, animated: true, completion: nil)
        }
        
    }
}


// MARK: - UITabBarControllerDelegate
extension WBTabBarViewController : UITabBarControllerDelegate {
    
    /// 点击tabbar的按钮，判断是不是从其他页面切换到主页的，如果不是就刷新主页数据并且滚动到顶部
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        //判断目标控制器是不是UIViewController
        let index = (childViewControllers as NSArray).index(of: viewController)
        
        if selectedIndex == index && index == 0 {
            
            let vc = (childViewControllers[0] as! UINavigationController).childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                
                vc.loadData()
            })
            
            vc.tabBarItem.badgeValue = nil
            
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        //判断目标控制器是不是UIViewController，是UIViewController就不弹出控制器
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: - 设置composeButton
extension WBTabBarViewController {
    
    ///设置composeButton
    fileprivate func setupComposeButton() {
        
        tabBar.addSubview(composeButton)
        
        composeButton.setImage(UIImage(named:"tabbar_composeButton"), for: .normal)
    composeButton.setBackgroundImage(UIImage(named:"tabbar_composeButton_background"), for: .normal)
        
        composeButton.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside)
        
        let count =  self.childViewControllers.count
        
        let width = tabBar.width / CGFloat(count)
        
        composeButton.frame = tabBar.bounds.insetBy(dx: width * 2, dy: 0)
    }
}


// MARK: - 设置新特性界面
extension WBTabBarViewController {
    
    /// 设置新特性界面
    fileprivate func setupNewFeature() {
        
        //0.判断是否登录
        if !WBNetworkManager.shared.userLogon {
            
            return
        }
        
        //1.检查版本是否更新
        
        //2.如果更新，显示新特性，否则显示欢迎

        let v = isNewVersion ? WBNewFeature.newFeatureView() : WBWelcomView.welcomeView()
        
        //3.添加视图
        v.frame = view.bounds
        
        view.addSubview(v)
    }
    
    /// 新版本属性
    private var isNewVersion : Bool {
        
        //1.获取当前版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        //2.获取沙盒中的版本号
        let version = UserDefaults.standard.string(forKey: "currentVersion")
        
        //3.将当前版本号存入沙盒
        UserDefaults.standard.set(currentVersion, forKey: "currentVersion")
        
        //4.比较两个版本号是否一致
        let isSame = (currentVersion == version) ? false : true
        
        return isSame
    }
}



// MARK: - 设置定时器
extension WBTabBarViewController {
    
    func setupTimer() {
        
        timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
    }
    
    
    /// 监听定时器的操作
    @objc private func updateTimer() {
        
        if !(WBNetworkManager.shared.userLogon)  {
            
            return
        }

        WBNetworkManager.shared.unreadCount { (count, isSuccess) in
            
   
            //更新tabbar首页按钮的红点数字提示
            self.tabBar.items?[0].badgeValue = (count == 0 ? nil : "\(count)" )
            
            //更新app图标的红点数字提示
            UIApplication.shared.applicationIconBadgeNumber = count 
        }
    }
}

// MARK: - 设置子控制器
extension WBTabBarViewController {
    
    ///设置子控制器
    fileprivate func setupChildControllers() {
        
        //从沙盒中读取json数据
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = docDir.appending("/main.json")
        var jsonData = NSData(contentsOfFile: jsonPath)
        
        if jsonData == nil {
            
            //从Bundle中读取json数据
            let bundlePath = Bundle.main.path(forResource: "main.json", ofType: nil)
            jsonData = NSData(contentsOfFile: bundlePath!)
        }
        
        guard let classArray = try? JSONSerialization.jsonObject(with: jsonData! as Data, options: []) as? [[String : AnyObject]]
            
            else {
            
                return
        }

        var childCtls = [UIViewController]()
        
        for dict in classArray! {
            
           let viewController = self.createChildController(dict: dict as [String : AnyObject])
            
            childCtls.append(viewController)
        }
        
        viewControllers = childCtls
    }
    
    /// 使用字典创建子控制器
    ///
    /// - parameter dict:信息字典（className, title, imageName， visitorInfo）
    ///
    /// - return: 子控制器
    private func createChildController(dict:[String : AnyObject]) -> UIViewController {
        
        guard let className = dict["className"] as? String,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let visitorDict = dict["visitorInfo"] as? [String: String],
              let clas = NSClassFromString(Bundle.main.nameSpace + "." + className) as? WBBaseViewController.Type
            
        else {
            
            return UIViewController()
        }
        
        //设置控制器
        let vc = clas.init()
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName + "_normal")
        
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //设置访客视图的数据
        vc.visitorInfoDictionary = visitorDict

        let nav = WBNaviViewController(rootViewController: vc)
        
        return nav
    }
    
}



